<template>
  <el-dialog :title="rolesForm.id?'编辑角色':'新增角色'" :visible="addRolesDialog" @close="closeDialog">
    <el-form ref="rolesForm" :model="rolesForm" :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item label="角色名称" prop="title">
        <el-input v-model="rolesForm.title" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="rolesForm.description" />
      </el-form-item>
      <el-form-item>
        <el-row type="flex" justify="center">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click.native="confirmFn">确定</el-button>
        </el-row>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { addRoles, updateRoles } from '@/api/roles'
export default {
  props: {
    addRolesDialog: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      rolesForm: {
        title: '',
        description: '',
        id: ''
      },
      rules: {
        title: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '角色名称长度为2-10个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' },
          { min: 2, max: 50, message: '角色名称长度为2-50个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 关闭弹窗
    closeDialog() {
      this.rolesForm = {
        title: '',
        description: ''
      } // 清空表单
      this.$refs.rolesForm.resetFields() // 清空验证
      this.$emit('update:addRolesDialog', false)
    },

    // 新增角色
    async confirmFn() {
      await this.$refs.rolesForm.validate() // 校验表单
      // 判断是新增还是编辑
      if (this.rolesForm.id) {
        await updateRoles(this.rolesForm)
      } else {
        await addRoles(this.rolesForm) // 新增角色
      }
      this.closeDialog() // 关闭弹窗
      this.$emit('loadRolesList') // 刷新页面
    }
  }
}
</script>

<style>

</style>
